#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import re
sys.path.append('src')

from processors.docx_processor import DOCXProcessor
from core.text_cleaner import TextCleaner

def debug_regex_matching():
    """调试正则表达式匹配问题"""
    
    print("=== 调试正则表达式匹配问题 ===")
    
    file_path = 'data/原始数据---选择题.docx'
    
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        return
    
    try:
        # 提取文档内容
        docx_processor = DOCXProcessor()
        with open(file_path, 'rb') as f:
            file_content = f.read()
        
        extraction_result = docx_processor.extract_content(file_content)
        raw_text = extraction_result['text']
        
        # 最小清洗
        cleaning_config = {
            'clean_unicode': False,
            'remove_special_chars': False,
            'fix_line_breaks': False,
            'remove_headers_footers': False,
            'remove_duplicates': False,
            'remove_empty_lines': False,
            'min_line_length': 0,
            'preserve_formatting': True
        }
        
        text_cleaner = TextCleaner(cleaning_config)
        cleaned_text = text_cleaner.clean_text(raw_text)
        
        print(f"原始文本长度: {len(raw_text)} 字符")
        print(f"清洗后文本长度: {len(cleaned_text)} 字符")
        
        # 分析文本行
        lines = cleaned_text.split('\n')
        print(f"\n总行数: {len(lines)}")
        
        # 测试不同的正则表达式模式
        patterns = [
            r'^\d+\.',
            r'^\s*\d+\.',
            r'^\s*\d+\s*\.',
            r'\d+\.',
            r'^\d+\.\s*'
        ]
        
        for pattern_str in patterns:
            print(f"\n=== 测试模式: {pattern_str} ===")
            pattern = re.compile(pattern_str, re.MULTILINE)
            
            # 在整个文本中查找
            matches = pattern.findall(cleaned_text)
            print(f"在整个文本中找到: {len(matches)} 个匹配")
            
            # 逐行检查
            matching_lines = []
            for i, line in enumerate(lines):
                line_stripped = line.strip()
                if pattern.match(line_stripped):
                    matching_lines.append((i, line_stripped))
            
            print(f"匹配的行数: {len(matching_lines)}")
            
            # 显示前10个匹配的行
            for j, (line_num, content) in enumerate(matching_lines[:10]):
                print(f"  行 {line_num}: {repr(content[:50])}...")
        
        # 详细分析前20行
        print(f"\n=== 前20行详细分析 ===")
        for i, line in enumerate(lines[:20]):
            line_repr = repr(line)
            line_stripped = line.strip()
            print(f"行 {i:2d}: {line_repr}")
            print(f"      去空格后: {repr(line_stripped)}")
            
            # 测试是否匹配数字+点模式
            if re.match(r'^\d+\.', line_stripped):
                print(f"      ✅ 匹配 ^\\d+\\.")
            else:
                print(f"      ❌ 不匹配 ^\\d+\\.")
            print()
        
        # 查找包含数字+点的所有行
        print(f"\n=== 包含数字+点的所有行 ===")
        digit_dot_lines = []
        for i, line in enumerate(lines):
            if re.search(r'\d+\.', line):
                digit_dot_lines.append((i, line.strip()))
        
        print(f"包含数字+点的行数: {len(digit_dot_lines)}")
        for i, (line_num, content) in enumerate(digit_dot_lines[:15]):
            print(f"  行 {line_num}: {content[:80]}...")
        
    except Exception as e:
        print(f"调试过程中出错: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    debug_regex_matching()